'use strict';

// 云对象名：admin-service
module.exports = {
  /**
   * 获取管理员信息
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @returns {object} 管理员信息
   */
  async getAdminInfo(userId, token) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 查询用户基本信息
      const userResult = await db.collection('users').doc(currentUserId).get();
      if (!userResult.data || userResult.data.length === 0) {
        return {
          code: -1,
          message: '用户不存在'
        };
      }
      
      const userInfo = Array.isArray(userResult.data) ? userResult.data[0] : userResult.data;
      
      // 查询管理员认证信息
      let adminCredential = null;
      const adminResult = await db.collection('admin_credentials').where({
        user_id: currentUserId
      }).get();
      
      if (adminResult.data && adminResult.data.length > 0) {
        adminCredential = adminResult.data[0];
      }
      
      // 构建返回数据
      const adminInfo = {
        _id: userInfo._id,
        username: userInfo.username,
        nickname: userInfo.nickname,
        email: userInfo.email,
        phone: userInfo.phone,
        role: userInfo.role,
        status: userInfo.status,
        create_date: userInfo.create_date,
        last_login_date: userInfo.last_login_date,
        credential_status: adminCredential?.status || 'pending',
        credential_type: adminCredential?.type || null,
        admin_level: adminCredential?.level || null,
        permissions: adminCredential?.permissions || []
      };
      
      return {
        code: 0,
        message: '获取成功',
        data: adminInfo
      };
    } catch (error) {
      console.error('获取管理员信息失败:', error);
      return {
        code: -1,
        message: '获取管理员信息失败: ' + error.message
      };
    }
  },

  /**
   * 获取管理员考试记录
   * @param {object} params - 参数对象
   * @param {string} params.examId - 考试ID
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @param {string} params.searchKeyword - 搜索关键词
   * @param {string} params.scoreFilter - 分数筛选
   * @param {string} params.token - 用户token
   * @returns {object} 考试记录列表
   */
  async getAdminExamRecords(params) {
    try {
      const db = uniCloud.database();
      const $ = db.command.aggregate;
      
      const { 
        examId,
        page = 1, 
        limit = 10,
        searchKeyword = '',
        scoreFilter = '全部分数',
        token
      } = params;
      
      if (!examId) {
        return {
          code: -1,
          message: '考试ID不能为空'
        };
      }
      
      // 构建查询条件
      const match = {
        exam_id: examId,
        status: 'completed'
      };
      
      // 添加分数筛选
      if (scoreFilter !== '全部分数') {
        const exam = await db.collection('exam_papers').doc(examId).get();
        const passScore = exam.data && exam.data.length > 0 ? (exam.data[0].pass_score || 60) : 60;
        
        switch (scoreFilter) {
          case '及格':
            match.score = db.command.gte(passScore);
            break;
          case '未及格':
            match.score = db.command.lt(passScore);
            break;
          case '优秀(90分以上)':
            match.score = db.command.gte(90);
            break;
          case '良好(75-89分)':
            match.score = db.command.and([
              db.command.gte(75),
              db.command.lt(90)
            ]);
            break;
          case '及格(60-74分)':
            match.score = db.command.and([
              db.command.gte(60),
              db.command.lt(75)
            ]);
            break;
          case '不及格(60分以下)':
            match.score = db.command.lt(60);
            break;
        }
      }
      
      // 添加关键词搜索
      if (searchKeyword) {
        // 先查询用户表获取匹配的用户ID
        const userResult = await db.collection('users')
          .where({
            nickname: new RegExp(searchKeyword, 'i')
          })
          .field({
            _id: true
          })
          .get();
          
        const userIds = userResult.data.map(u => u._id);
        
        if (userIds.length > 0) {
          match.user_id = db.command.in(userIds);
        } else {
          // 如果没有匹配的用户，返回空结果
          return {
            code: 0,
            data: [],
            total: 0
          };
        }
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询考试记录
      const recordsResult = await db.collection('exam_records')
        .aggregate()
        .match(match)
        .lookup({
          from: 'users',
          localField: 'user_id',
          foreignField: '_id',
          as: 'user_info'
        })
        .lookup({
          from: 'exam_papers',
          localField: 'exam_id',
          foreignField: '_id',
          as: 'exam_info'
        })
        .project({
          _id: 1,
          exam_id: 1,
          user_id: 1,
          score: 1,
          submit_time: 1,
          used_time: 1,
          status: 1,
          'user_info.nickname': 1,
          'user_info.avatar': 1,
          'exam_info.pass_score': 1
        })
        .skip(skip)
        .limit(limit)
        .end();
        
      // 查询总数
      const countResult = await db.collection('exam_records')
        .where(match)
        .count();
        
      // 处理返回数据
      const records = (recordsResult.data || []).map(record => {
        const userInfo = record.user_info && record.user_info[0] || {};
        return {
          _id: record._id,
          userInfo: {
            avatar: userInfo.avatar,
            nickname: userInfo.nickname
          },
          user_name: userInfo.nickname || '未知用户',
          createTime: record.submit_time,
          score: record.score || 0,
          isPassed: (record.score || 0) >= (record.pass_score || 60)
        };
      });
      
      return {
        code: 0,
        message: '获取成功',
        data: records,
        total: countResult.total
      };
    } catch (error) {
      console.error('获取管理员考试记录失败:', error);
      return {
        code: -1,
        message: '获取考试记录失败: ' + error.message
      };
    }
  },

  /**
   * 更新管理员状态
   * @param {string} adminId - 管理员ID
   * @param {string} status - 状态
   * @param {string} operatorId - 操作者ID
   * @returns {object} 更新结果
   */
  async updateAdminStatus(adminId, status, operatorId) {
    try {
      const db = uniCloud.database();
      
      if (!adminId || !status) {
        return {
          code: -1,
          message: '参数不完整'
        };
      }
      
      // 更新管理员状态
      await db.collection('users').doc(adminId).update({
        status: status,
        update_time: new Date()
      });
      
      // 更新管理员认证状态
      await db.collection('admin_credentials')
        .where({ user_id: adminId })
        .update({
          status: status,
          update_time: new Date(),
          operator_id: operatorId
        });
      
      return {
        code: 0,
        message: '状态更新成功'
      };
    } catch (error) {
      console.error('更新管理员状态失败:', error);
      return {
        code: -1,
        message: '更新状态失败: ' + error.message
      };
    }
  },

  /**
   * 获取我发布的考试
   * @param {object} params - 参数对象
   * @param {string} params.creatorId - 创建者ID
   * @param {string} params.token - 用户token
   * @param {number} params.page - 页码
   * @param {number} params.limit - 每页数量
   * @param {string} params.keyword - 关键词
   * @param {string} params.status - 状态筛选
   * @returns {object} 考试列表
   */
  async getMyPublishedExams(params) {
    try {
      const db = uniCloud.database();
      const $ = db.command.aggregate;
      
      // 参数解构
      const { 
        creatorId, 
        token, 
        page = 1, 
        limit = 10, 
        keyword,
        status
      } = params;
      
      // 获取当前用户信息
      let currentUserId = creatorId;
      
      if (!currentUserId && token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 构建查询条件
      const where = {
        $or: [
          { creator_id: currentUserId },
          { creatorId: currentUserId },
          { author_id: currentUserId },
          { user_id: currentUserId }
        ],
        status: db.command.neq('deleted'), // 排除已删除的试卷
        is_published: true // 只显示已发布的试卷
      };
      
      // 添加关键词搜索
      if (keyword) {
        where.title = db.command.regExp({
          regexp: keyword,
          options: 'i'
        });
      }
      
      // 添加状态筛选
      if (status && status !== '全部') {
        where.status = status;
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 使用聚合查询获取考试列表和统计信息
      const examList = await db.collection('exam_papers')
        .aggregate()
        .match(where)
        .lookup({
          from: 'exam_records',
          let: {
            exam_id: '$_id'
          },
          pipeline: $.pipeline()
            .match(db.command.expr($.eq(['$exam_id', '$$exam_id'])))
            .group({
              _id: null,
              participantCount: $.sum(1),
              totalScore: $.sum('$score')
            })
            .done(),
          as: 'examStats'
        })
        .addFields({
          participantCount: $.ifNull([$.arrayElemAt(['$examStats.participantCount', 0]), 0]),
          avgScore: $.cond({
            if: $.gt([$.arrayElemAt(['$examStats.participantCount', 0]), 0]),
            then: $.divide([
              $.arrayElemAt(['$examStats.totalScore', 0]),
              $.arrayElemAt(['$examStats.participantCount', 0])
            ]),
            else: 0
          }),
          examType: '$exam_type' // 添加考试类型字段
        })
        .project({
          examStats: 0 // 移除中间统计结果
        })
        .sort({
          create_date: -1
        })
        .skip(skip)
        .limit(limit)
        .end();
      
      // 查询总数
      const countResult = await db.collection('exam_papers')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: examList.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取我发布的考试失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取我发布的通知
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} keyword - 关键词
   * @param {string} category - 分类
   * @param {string} status - 状态
   * @returns {object} 通知列表
   */
  async getMyPublishedNotices(userId, token, page = 1, limit = 10, keyword, category, status) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 构建查询条件
      const where = {
        $or: [
          { userId: currentUserId },
          { creator_id: currentUserId }
        ]
      };
      
      // 排除已删除的
      where.status = db.command.neq('deleted');
      
      // 添加关键词搜索
      if (keyword) {
        where.title = db.command.regExp({ regexp: keyword, options: 'i' });
      }
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 添加状态筛选
      if (status && status !== '全部' && status !== 'deleted') {
        where.status = status;
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询通知列表
      const noticesResult = await db.collection('notices')
        .where(where)
        .orderBy('publishDate', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('notices')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: noticesResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取我发布的通知失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取我发布的规则
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} keyword - 关键词
   * @param {string} category - 分类
   * @returns {object} 规则列表
   */
  async getMyPublishedRules(userId, token, page = 1, limit = 10, keyword, category) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 构建查询条件
      const where = {
        $or: [
          { userId: currentUserId },
          { creator_id: currentUserId }
        ]
      };
      
      // 排除已删除的
      where.status = db.command.neq('deleted');
      
      // 添加关键词搜索
      if (keyword) {
        where.title = db.command.regExp({ regexp: keyword, options: 'i' });
      }
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询规则列表
      const rulesResult = await db.collection('rules')
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('rules')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: rulesResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取我发布的规则失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  },

  /**
   * 获取我发布的视频
   * @param {string} userId - 用户ID
   * @param {string} token - 用户token
   * @param {number} page - 页码
   * @param {number} limit - 每页数量
   * @param {string} keyword - 关键词
   * @param {string} category - 分类
   * @returns {object} 视频列表
   */
  async getMyPublishedVideos(userId, token, page = 1, limit = 10, keyword, category) {
    try {
      const db = uniCloud.database();
      
      // 获取当前用户信息
      let currentUserId = '';
      
      if (userId) {
        currentUserId = userId;
      } else if (token) {
        try {
          const tokenResult = await db.collection('users').where({
            token: token
          }).get();
          
          if (tokenResult.data && tokenResult.data.length > 0) {
            currentUserId = tokenResult.data[0]._id;
          }
        } catch (error) {
          console.error('解析token出错:', error);
        }
      }
      
      if (!currentUserId) {
        return {
          code: -1,
          message: '用户未认证'
        };
      }
      
      // 构建查询条件
      const where = {
        $or: [
          { userId: currentUserId },
          { creator_id: currentUserId }
        ]
      };
      
      // 排除已删除的
      where.status = db.command.neq('deleted');
      
      // 添加关键词搜索
      if (keyword) {
        where.title = db.command.regExp({ regexp: keyword, options: 'i' });
      }
      
      // 添加分类筛选
      if (category && category !== '全部') {
        where.category = category;
      }
      
      // 计算跳过数量
      const skip = (page - 1) * limit;
      
      // 查询视频列表
      const videosResult = await db.collection('videos')
        .where(where)
        .orderBy('create_date', 'desc')
        .skip(skip)
        .limit(limit)
        .get();
      
      // 查询总数
      const countResult = await db.collection('videos')
        .where(where)
        .count();
      
      return {
        code: 0,
        message: '获取成功',
        data: videosResult.data || [],
        total: countResult.total,
        page: page,
        limit: limit
      };
    } catch (error) {
      console.error('获取我发布的视频失败:', error);
      return {
        code: -1,
        message: '获取失败: ' + error.message
      };
    }
  }
}; 